package com.selen.mapper;

import com.selen.entities.Permission;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Selen
 */
@Repository
public interface PermissionMapper {
    @Insert("insert into ums_permission (`title`, `url`, " +
            "`icon`, `pid`, `info`, `deleted`, `created`, `updated`) " +
            "values (#{title},#{url}, #{icon},#{pid}, #{info}, " +
            " #{deleted}, #{created}, #{updated})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Permission permission);

    @Select("select us.id, us.title, us.url, us.icon, us.pid, us.info, " +
            "us.deleted, us.created, us.updated from  ums_permission us " +
            "where us.id = #{param1} and us.deleted = 0")
    Permission selectById(Long id);

    @Update("<script>" +
            "update ums_permission " +
            "<set> " +
            "<if test='title     != null'>  title       =  #{title}    , </if> " +
            "<if test='url       != null'>  url         =  #{url}      , </if> " +
            "<if test='icon      != null'>  icon        =  #{icon}     , </if> " +
            "<if test='pid       != null'>  pid         =  #{pid}      , </if> " +
            "<if test='info      != null'>  info        =  #{info}     , </if> " +
            "<if test='deleted   != null'>  deleted     =  #{deleted}  , </if> " +
            "<if test='created   != null'>  created     =  #{created}  , </if> " +
            "<if test='updated   != null'>  updated     =  #{updated}  , </if> " +
            "</set> " +
            "where id = #{id} and deleted = 0 " +
            "</script>")
    int updateById(Permission permission);

    @Update("update ums_permission set deleted = 1, updated = now() where id = #{param1}")
    int logicDeleteById(Long id);

    @Update("<script>" +
            "update ums_permission set deleted = 1, updated = now() where" +
            "<foreach collection = 'list' item = 'e' open = 'id in (' close = ')' separator = ','>" +
            "${e}" +
            "</foreach>" +
            "</script>")
    int logicDeleteByIds(List<Long> ids);

    @Select("select us.id, us.title, us.url, us.icon, us.pid, us.info, " +
            "us.deleted, us.created, us.updated from  ums_permission us where us.deleted = 0")
    List<Permission> list();

    @Delete("delete from  ums_permission where id = #{param1}")
    int deleteById(Long id);

    @Select("select up.id, up.title, up.url, up.icon, up.pid, up.info, up.deleted, up.created, up.updated " +
            "from ums_permission as up " +
            "where up.id in (" +
            "select urp.fk_permission_id " +
            "from ums_role_permission as urp " +
            "where urp.fk_role_id in (select uer.fk_role_id " +
            "from ums_emp_role as uer " +
            "where uer.fk_emp_id = #{id}));")
    List<Permission> selectByEmpId(Long id);
}
